<?php

require_once ("secure_area.php");

class Laybys extends Secure_area {

    function __construct() {
        parent::__construct('laybys');
        $this->load->model('lay');
        $this->load->model('Sale');
    }

    function invoice($sale_id) {
        $data = array();
        $data['layby_sale_id'] = $sale_id;
        $data['cart'] = $this->lay->get_sale_items($data['layby_sale_id'])->result_array();
        for ($index = 0; $index < count($data['cart']); $index++) {
            $data['cart'][$index]['quantity'] = $data['cart'][$index]['quantity_purchased'];
            $data['cart'][$index]['discount'] = $data['cart'][$index]['discount_percent'];
            $data['cart'][$index]['price'] = $data['cart'][$index]['item_unit_price'];
        }
        $data['sales'] = $this->Sale->get_info($data['layby_sale_id']);
        $data['items_in_cart'] = $this->lay->get_items_in_cart($data['layby_sale_id']);
        $data['subtotal'] = $this->lay->get_subtotal($data['layby_sale_id']);
        $data['total'] = $this->lay->get_total($data['layby_sale_id']);
        $data['taxes'] = $this->lay->get_taxes($data['layby_sale_id']);
        $data['balance'] = $this->lay->get_balance($data['layby_sale_id']);
        $data['amount_due'] = $data['balance'];
        $customer_id = $this->lay->get_customer_id($data['layby_sale_id']);
        $comment = $this->lay->get_comment();
        $data['deposits'] = $this->lay->get_deposit_list($data['layby_sale_id']);
       
        $data['receipt_title'] = ($data['balance'] == 0 ? lang('sale_tax_receipt') : lang('layby_receipt'));
        $employee_id = $this->Employee->get_logged_in_employee_info()->person_id;
        $emp_info = $this->Employee->get_info($employee_id);
         
        $data['employee'] = $emp_info->first_name . ' ' . $emp_info->last_name;

        if ($customer_id != -1 or !is_null($customer_id)) {
            $cust_info = $this->Customer->get_info($customer_id);
            $data['customer'] = $cust_info->first_name . ' ' . $cust_info->last_name . ($cust_info->company_name == '' ? '' : ' (' . $cust_info->company_name . ')');
            $data['customer_address'] = $cust_info->address_1;
            $data['customer_suburd'] = $cust_info->suburd;
            $data['customer_state'] = $cust_info->state;
            $data['customer_postcode'] = $cust_info->zip;
            $data['customer_phone'] = $cust_info->phone_number;
        }
        
        $this->load->view("laybys/invoice", $data);
    }

    function index() {
        $config['base_url'] = site_url('laybys/index');
        $config['total_rows'] = $this->lay->count_all();
        $config['per_page'] = $this->config->item('number_of_items_per_page') ? (int) $this->config->item('number_of_items_per_page') : 20;
        $this->pagination->initialize($config);
        $data['controller_name'] = strtolower(get_class());
        $data['form_width'] = $this->get_form_width();
        $data['manage_table'] = get_layby_manage_table($this->lay->get_all($config['per_page'], $this->uri->segment(3)), $this);
        $this->load->view('laybys/manage', $data);
    }

    /*
      Returns customer table data rows. This will be called with AJAX.
     */

    function search() {
        $search = $this->input->post('search');
        $data_rows = get_layby_manage_table_data_rows($this->lay->search($search, $this->config->item('number_of_items_per_page') ? (int) $this->config->item('number_of_items_per_page') : 20), $this);
        echo $data_rows;
    }

    /*
      Gives search suggestions based on what is being searched for
     */

    function suggest() {
        $suggestions = $this->lay->get_layby_search_list_suggestions($this->input->get('term'), 100);
        echo json_encode($suggestions);
    }

    /*
      Inserts/updates a customer
     */

    function save($customer_id = -1) {
        $person_data = array(
            'first_name' => $this->input->post('first_name'),
            'last_name' => $this->input->post('last_name'),
            'email' => $this->input->post('email'),
            'phone_number' => $this->input->post('phone_number'),
            'address_1' => $this->input->post('address_1'),
            //'address_2'=>$this->input->post('address_2'),
            //'city'=>$this->input->post('city'),
            'state' => $this->input->post('state'),
            'suburd' => $this->input->post('suburd'),
            'zip' => $this->input->post('zip')
                //'country'=>$this->input->post('country'),
                //'comments'=>$this->input->post('comments')
        );
        $customer_data = array(
            'company_name' => $this->input->post('company_name'),
            'account_number' => $this->input->post('account_number') == '' ? null : $this->input->post('account_number'),
            'taxable' => $this->input->post('taxable') == '' ? 0 : 1,
        );

        if ($this->Customer->save($person_data, $customer_data, $customer_id)) {
            /* if ($this->config->item('mailchimp_api_key'))
              {
              $this->Person->update_mailchimp_subscriptions($this->input->post('email'), $this->input->post('first_name'), $this->input->post('last_name'), $this->input->post('mailing_lists'));
              } */
            //New customer
            if ($customer_id == -1) {
                echo json_encode(array('success' => true, 'message' => lang('customers_successful_adding') . ' ' .
                    $person_data['first_name'] . ' ' . $person_data['last_name'], 'person_id' => $customer_data['person_id']));
            } else { //previous customer
                echo json_encode(array('success' => true, 'message' => lang('customers_successful_updating') . ' ' .
                    $person_data['first_name'] . ' ' . $person_data['last_name'], 'person_id' => $customer_id));
            }
        } else {//failure
            echo json_encode(array('success' => false, 'message' => lang('customers_error_adding_updating') . ' ' .
                $person_data['first_name'] . ' ' . $person_data['last_name'], 'person_id' => -1));
        }
    }

    /*
      This deletes customers from the customers table
     */

    function delete() {
        $customers_to_delete = $this->input->post('ids');

        if ($this->Customer->delete_list($customers_to_delete)) {
            echo json_encode(array('success' => true, 'message' => lang('customers_successful_deleted') . ' ' .
                count($customers_to_delete) . ' ' . lang('customers_one_or_multiple')));
        } else {
            echo json_encode(array('success' => false, 'message' => lang('customers_cannot_be_deleted')));
        }
    }

    function excel() {
        $data = file_get_contents("import_customers.csv");
        $name = 'import_customers.csv';
        force_download($name, $data);
    }

    function excel_import() {
        $this->load->view("customers/excel_import", null);
    }

    function do_excel_import() {
        $msg = 'do_excel_import';
        $failCodes = array();
        if ($_FILES['file_path']['error'] != UPLOAD_ERR_OK) {
            $msg = lang('items_excel_import_failed');
            echo json_encode(array('success' => false, 'message' => $msg));
            return;
        } else {
            if (($handle = fopen($_FILES['file_path']['tmp_name'], "r")) !== FALSE) {
                //Skip first row
                fgetcsv($handle);

                $i = 1;
                while (($data = fgetcsv($handle)) !== FALSE) {
                    $person_data = array(
                        'first_name' => $data[0],
                        'last_name' => $data[1],
                        'email' => $data[2],
                        'phone_number' => $data[3],
                        'address_1' => $data[4],
                        //'address_2'=>$data[5],
                        //'city'=>$data[5],
                        'state' => $data[5],
                        'suburd' => $data[6],
                        'zip' => $data[7]
                            //'country'=>$data[9],
                            //'comments'=>$data[10]
                    );
                    /*
                      $customer_data=array(
                      'account_number'=>$data[11]=='' ? null:$data[11],
                      'taxable'=>$data[12]=='' ? 0:1,
                      'company_name' => $data[13],
                      );
                     */
                    if (!$this->Customer->save($person_data, $customer_data)) {
                        $failCodes[] = $i;
                    }

                    $i++;
                }
            } else {
                echo json_encode(array('success' => false, 'message' => lang('common_upload_file_not_supported_format')));
                return;
            }
        }

        $success = true;
        if (count($failCodes) > 1) {
            $msg = lang('customers_most_imported_some_failed') . " (" . count($failCodes) . "): " . implode(", ", $failCodes);
            $success = false;
        } else {
            $msg = lang('customers_import_successfull');
        }

        echo json_encode(array('success' => $success, 'message' => $msg));
    }

    /*
      get the width for the add/edit form
     */

    function get_form_width() {
        return 550;
    }

}

?>